#!/usr/bin/python2.5
# Copyright (c) 2008 MalFind

__author__ = "mavrommatis@gmail.com (Panayiotis Mavrommatis)"

import urllib
import httplib
import time

hashes = []
count = 0

def AddHashes(hashes):
  body = urllib.urlencode({"adds": ",".join(hashes)})

  headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': len(body),
  }

  try:
    # conn = httplib.HTTPConnection("localhost:8080")
    conn = httplib.HTTPConnection("malfind.appspot.com")
    conn.request("POST", "/update", body, headers)
    response = conn.getresponse()
    conn.close()
    print response.status, response.reason
    return response.status == 200

  except Exception, e:
    print e
    return False


def TryAddHashes(hashes):
  retries = 0
  while retries < 2:
    if AddHashes(hashes):
      hashes = []
      break
    
    print "Error, Retrying in 60 secs"
    time.sleep(60)
    retries += 1
    
  if retries == 2:
    print "Too many errors, aborting"
    sys.exit(-1)


for line in open('/tmp/sbcache.txt'):
  if not line[0] == '+':
    print 'Ignoring ' + line.strip('\n')
    continue

  count += 1
  if count < 19000:
    continue

  hashes.append(line.strip('+').strip('\t\n'))

  if count % 50 == 0:
    print count
    TryAddHashes(hashes)
    hashes = []
    time.sleep(0.2)
        
TryAddHashes(hashes)

print "Success"
